package com.f37.f37ex01.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.f37.f37ex01.bean.Customer;
import com.f37.f37ex01.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 35837
 * @version 1.0
 * @since 2023-12-29 16:03:14
 */
@Controller
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    // 登录
    @PostMapping("/login")
    public String login(String username, String password, HttpSession session, ModelMap map) {
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        Map<String, String> cus = new HashMap<>();
        cus.put("username", username);
        cus.put("password", password);
        wrapper.allEq(cus);
        if (customerService.count(wrapper) != 0) {
            Customer customer = customerService.login(wrapper);
            session.setAttribute("customer", customer);
            // 登录成功
            return "index";
        } else {
            // 登录失败
            map.addAttribute("msg", "用户名或密码错误");
            return "login";
        }
    }

    // 注册
    @PostMapping("/register")
    public String register(String username, String password, String nick, ModelMap map) {
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        if (customerService.count(wrapper) != 0) {
            map.addAttribute("msg", "用户名已存在");
            return "register";
        } else {
            customerService.register(username, password, nick);
            map.addAttribute("msg", "注册成功");
            return "login";
        }
    }
}
